package com.polaris.live.ui.set

import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.R
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.event.EventMessage
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ImmersionBarBuilder
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.ActivityBindPhoneBinding
import com.polaris.live.manager.AssetsConfigManager
import com.polaris.live.resp.back_resp.AreaCodeResp
import com.polaris.live.translation.R.string
import com.polaris.live.ui.login.AreaCodeActivity
import com.polaris.live.ui.login.BaseGoogleLoginActivity
import com.polaris.live.ui.login.verify.VerifyActivity
import com.polaris.live.utils.AutoSeparateTextWatcher
import com.polaris.live.viewmodel.login.PhoneNumberModel
import com.polaris.live.widget.country.countryIcons
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 绑定手机号
 *
 * @author Created by 长空 on 2023/10/21
 */
class BindPhoneActivity : BaseGoogleLoginActivity<PhoneNumberModel, ActivityBindPhoneBinding>() {

    private var mCountryCode = ""

    private var mAreaCode = ""
    private var mPhoneNumber = ""

    override fun ImmersionBarBuilder.buildImmersionBar() {
        setTitleBar(mBinding.bvTitle)
        setStatusBarDarkFont(false)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        EventBus.getDefault().register(this)
        mViewModel.getIp()

        initListener()
        initObserve()
    }

    private fun initListener() {
        val textWatcher = AutoSeparateTextWatcher(mBinding.phoneNumberEdit)
        textWatcher.setRules(intArrayOf(3, 4, 4, 4, 4, 4))
        textWatcher.separator = ' '
        mBinding.phoneNumberEdit.addTextChangedListener(textWatcher)

        textWatcher.setAddTextChanage {
            val toString = mBinding.phoneNumberEdit.text.toString()
            val trimmedStr = toString.replace("\\s+".toRegex(), "")  // 去掉所有空格

            if (trimmedStr.length < 7) {
                mBinding.loginButton.alpha = AppConst.NOTCLICK
            } else {
                mBinding.loginButton.alpha = 1.0f
            }
        }

        mBinding.loginButton.setOnSingleClickListener {
            val toString = mBinding.phoneNumberEdit.text.toString()
            mPhoneNumber = toString.replace("\\s+".toRegex(), "")  // 去掉所有空格

            val phoneCode = mBinding.phoneAreaCode.text.toString()
            mAreaCode = phoneCode.substring(1)

            if (mPhoneNumber.length >= 7) {
                mViewModel.isRegistered(mAreaCode, mPhoneNumber)
            }
        }
        mBinding.phoneAreaCode.setOnSingleClickListener {
            val intent = Intent(this, AreaCodeActivity::class.java)
            intent.putExtra("countryCode", mCountryCode)
            areaCodeRegister.launch(intent)
        }
        mBinding.phoneNumberClear.setOnSingleClickListener {
            mBinding.phoneNumberEdit.setText("")
        }
    }

    private fun initObserve() {
        mViewModel.ipLiveData.observe(this) {
            mCountryCode = it ?: "CA"

            val areaCodeBean = AssetsConfigManager.getAreaCode(mCountryCode)
            if (areaCodeBean != null) {
                updateAreaCode(areaCodeBean)
            } else {
                mViewModel.getAreaCodeByCountryCode(mCountryCode)
            }
        }
        mViewModel.areaCodeLiveData.observe(this) {
            updateAreaCode(it)
        }

        mViewModel.isRegisteredLiveData.observe(this) { state ->
            parseState(state, { resp ->
                if (resp.registered == true) {
                    ToastGravity.showGravity(StringUtils.getString(string.phone_is_registered))
                    return@parseState
                }
                verifyGoogle {
                    val intent = Intent()
                    intent.setClass(this, VerifyActivity::class.java)
                    intent.putExtra("phoneNumber", mBinding.phoneNumberEdit.text.toString())
                    intent.putExtra("areaCode", mAreaCode)
                    intent.putExtra("bind", true)
                    if (it != null) {
                        intent.putExtra("googleValidate", it)
                    }
                    startActivity(intent)
                }
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    private fun updateAreaCode(resp: AreaCodeResp) {
        mBinding.phoneNumberImg.setImageResource(resp.countryCode?.let { countryIcons[it] }
            ?: R.color.gray)
        mBinding.phoneAreaCode.text = "+${resp.areaCode}"
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: EventMessage) {
        when (event.from) {
            BizEventConst.BIND_SUCCESS -> {//绑定手机号后销毁这页
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private val areaCodeRegister =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val resp = result.data?.getParcelableExtra<AreaCodeResp>("areaCode")
                resp?.also { updateAreaCode(it) }
            }
        }
}